package cn.mily.user.service.impl;

import cn.mily.basics.constant.Constant;
import cn.mily.basics.exception.UtilException;
import cn.mily.basics.utils.JsonResult;
import cn.mily.basics.utils.MD5Utils;
import cn.mily.user.domain.LoginInfo;
import cn.mily.user.mapper.LoginInfoMapper;
import cn.mily.user.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LoginInfoMapper mapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录 + 记住我
     * @param loginInfo 登录信息
     * @return
     */
    @Override
    @Transactional
    public JsonResult login(LoginInfo loginInfo) throws UtilException {
        /*效验*/
        checkLoginInfo(loginInfo);
        /*检查登录信息*/
        LoginInfo login = mapper.loginByUserName(loginInfo.getUsername(),loginInfo.getType());
        /*查询有该用户*/
        if(login==null){
            throw new UtilException("没有此用户！");
        }
        /*检查密码正确*/
        if(!MD5Utils.encrypByMd5(loginInfo.getPassword()+login.getSalt()).equals(login.getPassword())){
            throw new UtilException("密码错误！");
        }
        /*创建会话跟踪*/
        String token = UUID.randomUUID().toString();
        /*将数据存入redis中设置过期时间*/
        redisTemplate.opsForValue().set(token, login,30, TimeUnit.MINUTES);
        /*封装数据*/
        /*Map<String,Object> map = new HashMap<>();
        map.put("user",login);
        map.put("token", token);*/
        /*将数组返回前端*/
        JsonResult jsonResult = new JsonResult();
        jsonResult.setResultObj(token);

        /*记住我功能*/
        /*判断记住我选择框是否选择  已选择*/
        /*if(remember_me){
            *//*将用户登录信息保存在cookie中*//*
            Cookie cookie_name = new Cookie("username",
                    StringUtils.isEmpty(login.getUsername())?(StringUtils.isEmpty(login.getPhone())?login.getEmail():login.getPhone()):login.getUsername());
            Cookie cookie_password = new Cookie("password", login.getPassword());
            *//*设置cookie有效路径*//*
            cookie_name.setPath("http://localhost:8082");
            cookie_password.setPath("http://localhost:8082");
            *//*设置cookie 生存时间*//*
            cookie_name.setMaxAge(15 * 24 * 60 * 60);
            cookie_password.setMaxAge(15 * 24 * 60 * 60);
            *//*cookie响应前端*//*
            response.addCookie(cookie_name);
            response.addCookie(cookie_password);
        }else{
            *//*摧毁cookie*//*
            Cookie[] cookies = request.getCookies();
            if(cookies!=null){
                for (Cookie cookie : cookies) {
                    if(cookie.equals("username")||cookie.equals("password")) {
                        cookie.setMaxAge(0);
                        cookie.setPath("http://localhost:8082");
                        response.addCookie(cookie);
                    }
                }
            }
        }*/
        return jsonResult;
    }

    /**
     * 邮箱 验证码 登录
     * @param loginInfo
     */
    @Override
    @Transactional
    public JsonResult loginByEmail(LoginInfo loginInfo) throws UtilException {
        /*效验  邮箱和密码*/
        checkLoginInfo(loginInfo);
        /*验证码效验*/
        String s = (String)redisTemplate.opsForValue().get(loginInfo.getUsername() + ":" + Constant.USER_EMAIL);
        /*在redis中无对应验证码*/
        if(s==null){
            throw new UtilException("抱歉！验证码已过期！请重新获取！");
        }
        /*有验证码判断 对*/
        if(!s.toUpperCase().equals(loginInfo.getPassword().toUpperCase())){
            throw new UtilException("抱歉！验证码错误！");
        }
        /*成功  将用户信息存入redis中*/
        LoginInfo login = mapper.loginByUserName(loginInfo.getUsername(), loginInfo.getType());
        /*产生token*/
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,login);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setResultObj(token);
        return jsonResult;
    }

    /**
     * 效验
     * @param loginInfo
     * @return
     */
    private void checkLoginInfo(LoginInfo loginInfo) throws UtilException {
        /*用户名 手机号 验证码*/
        if(StringUtils.isEmpty(loginInfo.getUsername())){
            throw new UtilException("抱歉用户名(手机/邮箱)未填写！");
        }
        /*用户表中查询*/
        LoginInfo login = mapper.loginByUserName(loginInfo.getUsername(), loginInfo.getType());
        /*判断该用户注册没*/
        if(login==null){
            /*用户名邮箱*/
            loginInfo.setEmail(loginInfo.getUsername());
            loginInfo.setUsername(null);
            mapper.add(loginInfo);
        }
        /*用户密码*/
        if(StringUtils.isEmpty(loginInfo.getPassword())){
            throw new UtilException("请填写密码！");
        }
    }
}
